import { constantRoutes, asyncRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(flags, route) {
	if(route.meta && route.meta.flag) {
		return flags.includes(route.meta.flag)
	} else {
		return true
	}
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, flags) {
	const res = []
	routes.forEach(route => {
		const tmp = { ...route}
		if(hasPermission(flags, tmp)) {
			if(tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, flags)
			}
			res.push(tmp)
		}
	})
	return res
}

const state = {
	routes: [],
	addRoutes: []
}

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.addRoutes = routes
		state.routes = constantRoutes.concat(routes)
	}
}

const actions = {
	generateRoutes({commit}, {flags}) {
		return new Promise(resolve => {
			let accessedRoutes = filterAsyncRoutes(asyncRoutes, flags)
			commit('SET_ROUTES', accessedRoutes)
			resolve(accessedRoutes)
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}